// pages/waiter/usercheckdetail/usercheckdetail.js
import Big from 'big.js'
const request = require('@/utils/request.js')
const constants = require('@/utils/khyConstants.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    sctp_img:getApp().globalData.nginxIp+'/img/sctp.png',
    orderInfo: {},
    payModeList: getApp().globalData.dictData['payMode'],
    insureStatusList: getApp().globalData.dictData['insureStatus'],
    goodsTypeList: getApp().globalData.dictData['goodsType'],
    outerPackTypeList: getApp().globalData.dictData['outerPackType'],
    storageRate: getApp().globalData.storageRate,//保管费率20%
    requireList: {
      signPhoto: '请选择签收照片',
      storageCost: '请填写保管费用',

    },
    payModeName: '',
    goodsTypeName: '',
    insureStatusName: '',
    outerPackTypeName: '',
    imgList:[],// 上传的图片
    signImgList:[],// 签收上传的图片
    stepList: [
      {label:'已下单', content: '暂无', time: ''},
      {label:'已揽收', content: '暂无', time: ''},
      {label:'运输中', content: '暂无', time: ''},
      {label:'已送达', content: '暂无', time: ''},
      {label:'已签收', content: '暂无', time: ''},
    ],
    currentStep: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getPageData()
  },

  getPageData() {
    let order = getApp().globalData.pageData[constants.page_usercheckdetail]
    if (order && order.keyId) {
      request.get('/UserController/getOrderLogisticsById', {keyId: order.keyId}).then(res => {
        if (res.data.code == constants.resultSuccessCode &&
          res.data.result) {
            let shouTime = ''
            let data = res.data.result || []
            let newStepList = this.data.stepList
            for (let i = 0, n = newStepList.length; i < n; i++) {
              if (i < data.length) {
                newStepList[i]['content'] = data[i]['logisticsDesc']
                newStepList[i]['time'] = data[i]['logisticsTime']
              } else {
                newStepList[i]['content'] = '暂无'
                newStepList[i]['time'] = ''
              }

              if (i == 3 && data[i]) {
                shouTime = data[i]['logisticsTime']
              }
            }

            let storageCost = 0
            if (shouTime) {
              shouTime = shouTime.replaceAll("-", "/");
              var dateBegin = new Date(shouTime);
              var dateEnd = new Date(); //获取当前时间
              var dateDiff = dateEnd.getTime() - dateBegin.getTime(); //时间差的毫秒数
              var dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000)); //计算出相差天数

              let goodsFreight = order.goodsFreight
              storageCost = new Big(goodsFreight).times(new Big(dayDiff)).times(new Big(this.data.storageRate)).round(2,Big.roundUp).toNumber()
            }

            this.setData({
              stepList: newStepList,
              currentStep: (data.length == 0 ? 0 : data.length - 1),
              'orderInfo.storageCost': storageCost
            })
        }
      })


      let obj = {}
      obj.orderInfo = order
      if (order['payMode']) {
        obj.payModeName = this.data.payModeList[order['payMode'] -1]['label']
      }
      if (order['goodsType']) {
        this.data.goodsTypeList.forEach(item => {
          if (order['goodsType'] == item['value']) {
            obj.goodsTypeName = item['label']
          }
        })
      }
      if (order['insureStatus']) {
        this.data.insureStatusList.forEach(item => {
          if (order['insureStatus'] == item['value']) {
            obj.insureStatusName = item['label']
          }
        })
      }
      if (order['outerPackType']) {
        this.data.outerPackTypeList.forEach(item => {
          if (order['outerPackType'] == item['value']) {
            obj.outerPackTypeName = item['label']
          }
        })
            
      }
      if (order.goodsPhoto) {
        let goodsPhoto = order.goodsPhoto.split(",")
        let imgList=[];
        if(goodsPhoto.length>0){
          goodsPhoto.forEach((item)=>{
            if(item!= ""){
              imgList.push(getApp().globalData.nginxIp+"/"+item)
            }
          })
          obj['imgList']=imgList
        }
      }

      this.setData(obj)
    }
  },

  onInput(e) {
    let name = e.currentTarget.dataset.name
    let value = e.detail.value

    this.setData({
      [`orderInfo.${name}`]: value
    })
    
  },

  maxViewImg(e){
    let imgUrl=e.currentTarget.dataset.img
    wx.previewImage({
        current:imgUrl,
        urls: [imgUrl],
    })
  },

  /**
   * 添加图片
   */
  addPhone(){
    const app = getApp();
    let that=this;
    let signImgList = this.data.signImgList
    wx.chooseImage({
        count: 1, // 可选择的图片数量
        sizeType: ['compressed'], // 压缩图片
        sourceType: ['album', 'camera'], // 来源：相册或相机
        success: (res) => {
            signImgList.push(res.tempFilePaths[0])
            // 将选择的图片上传到服务器
            wx.uploadFile({
                url: app.globalData.uploadServer, //后端接口
                filePath: res.tempFilePaths[0],
                name: 'file',
                header: "application/json",
                success(res) {
                    let data = JSON.parse(res.data)
                    if(data.code == "200"){
                        let signPhoto = ''
                        if (that.data.orderInfo.signPhoto) {
                          signPhoto = that.data.orderInfo.signPhoto+","+data.message
                        } else {
                          signPhoto = data.message
                        }

                        that.setData({
                          signImgList: signImgList,
                          'orderInfo.signPhoto':signPhoto
                        });
                    }else{
                        wx.showToast({
                            title: res.data.message || '上传失败',
                            icon: 'error',
                            duration: 2000
                          })
                    }
                   
                },
                fail(e) {
                    console.log(e);
                }
            })
        },
        fail(e) {
            console.log(e+"上传失败");
        }
    })
  },

  orderCommit() {
    for (const key in this.data.requireList) {
      if (!this.data.orderInfo[key] && this.data.orderInfo[key] != 0) {
        wx.showToast({
          title: this.data.requireList[key],
          icon: 'error',
          duration: 2000
        })
        return
      }

    }
    
    let user = getApp().getUserInfo()
    let data = Object.assign({}, this.data.orderInfo, {
      tallyClerkSign: user.userNo, tallyClerkSignName: user.userName
    })
    request.post('/UserController/signPackage', data).then(res => {
      if (res.data.code == constants.resultSuccessCode) {
        wx.showToast({
          title: '签收成功',
          icon: 'success',
          duration: 2000,
          success: res => {
            setTimeout(function() {
              wx.navigateBack({delta:1})
            }, 2000)
          }
        })
      } else {
        wx.showToast({
          title: res.data.message || '下单失败',
          icon: 'error',
          duration: 2000
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})